package com.auth.domain.service.impl;

import com.auth.domain.module.po.authmanage.UserRole;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.auth.control.model.UserRoleDto;
import com.auth.domain.mapper.authmanage.UserRoleMapper;
import com.auth.domain.module.vo.authmanage.RoleVO;
import com.auth.domain.service.IRoleService;
import com.auth.domain.service.IUserRoleService;
import com.bean.ObjectMapperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户角色表 服务实现类
 * </p>
 *
 * @author cyj
 * @since 2020-10-21
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {

    @Autowired
    private IRoleService roleService;

    @Override
    public boolean removeByUserId(Long userId) {
        return remove(new QueryWrapper<>(new UserRole().setUserId(userId)));
    }

    @Override
    public List<UserRole> getByUserId(Long userId) {
        return this.baseMapper.selectList(new QueryWrapper<>(new UserRole().setUserId(userId)));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUserRoles(Long userId, List<UserRoleDto> userRoleDtos) {
        this.removeByUserId(userId);
        List<UserRole> userRoles = ObjectMapperUtils.clones(userRoleDtos, UserRole.class);
        this.saveBatch(userRoles);
    }

    @Override
    public List<RoleVO> getUserRoles(Long userId) {
        LambdaQueryWrapper<UserRole> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(UserRole::getUserId, userId);
        List<UserRole> list = this.list(lambdaQueryWrapper);
        Set<Long> roleIds = list.stream().map(UserRole::getRoleId).collect(Collectors.toSet());
        return roleService.getByIds(roleIds);
    }
}
